package com.sean.filter;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class StaticResourceFilter implements Filter {

    private static final String RESOURCE_BAST_PATH = "resourceBastPath";
    private String basePath;

    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
	    FilterChain chain) throws IOException, ServletException {
	if (request instanceof HttpServletRequest) {
	    HttpServletRequest req = (HttpServletRequest) request;
	    String uri = req.getRequestURI();
	    // find howto/xxx.swf request
	    Pattern pattern = Pattern.compile("(howto/.+\\.swf$)");
	    Matcher matcher = pattern.matcher(uri);
	    if (matcher.find()) {
		String path = matcher.group(0);
		// Read data from disk and transmit to response.
		InputStream is = new FileInputStream(getBasePath() + "/" + path);
		int iValue = -1;
		while ((iValue = is.read()) != -1) {
		    response.getOutputStream().write(iValue);
		}
		response.getOutputStream().flush();
		return;
	    }
	}

	chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
	setBasePath(filterConfig.getInitParameter(RESOURCE_BAST_PATH));
    }

    public String getBasePath() {
	return basePath;
    }

    public void setBasePath(String basePath) {
	this.basePath = basePath;
    }

}
